package by.demchenko.sample.webapp.page.admin;

import by.demchenko.sample.datamodel.Account;
import by.demchenko.sample.datamodel.Faculty;
import by.demchenko.sample.datamodel.Person;
import by.demchenko.sample.datamodel.enums.Gender;
import by.demchenko.sample.datamodel.enums.UserType;
import by.demchenko.sample.services.FacultyService;
import by.demchenko.sample.services.PersonService;
import by.demchenko.sample.services.UserService;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;

import javax.inject.Inject;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@AuthorizeInstantiation("ADMIN")
public class StudentEditPage extends BaseAdminPage {

    @Inject
    private PersonService personService;

    @Inject
    private UserService userService;

    @Inject
    private FacultyService facultyService;

    public StudentEditPage(final Person student) {
        super();
        add(new Label("headerTitle", getString("label.editor")));
        add(new Label("subtitle", getString("label.editor")));
        add(new FeedbackPanel("feedback"));

        Form<Person> form = new Form<>("form");

        form.add(createTextField(student, "firstName"));
        form.add(createTextField(student, "lastName"));
        form.add(createTextField(student, "middleName"));

        List<Faculty> facultyList = facultyService.getAll();
        final DropDownChoice<Faculty> tfFaculty = new DropDownChoice<>(
                "faculty",
                new PropertyModel<>(student, "faculty"),
                facultyList,
                new ChoiceRenderer<>("name", "id"));
        tfFaculty.setLabel(new ResourceModel("person.faculty"));
        tfFaculty.setRequired(true);
        form.add(tfFaculty);

        form.add(createDateField(student, "dateOfBirth"));

        final DropDownChoice<Gender> tfGender = new DropDownChoice<Gender>(
                "gender",
                new PropertyModel<>(student, "gender"),
                Arrays.asList(Gender.values()),
                new EnumChoiceRenderer<>(this));
        tfGender.add(new PropertyValidator<>());
        tfGender.setLabel(new ResourceModel("person.gender"));
        form.add(tfGender);

        form.add(createTextField(student, "phone"));

        Account newAccount = student.getId() == null ? new Account() : null;

        final TextField<String> tfLogin = new TextField<>("login", new PropertyModel<>(student.getId() == null ? newAccount : student.getAccount(), "login"));
        tfLogin.add(new PropertyValidator<>());
        tfLogin.setLabel(new ResourceModel("person.login"));
        form.add(tfLogin);

        final PasswordTextField tfPassword = new PasswordTextField("password", new PropertyModel<>(student.getId() == null ? newAccount : student.getAccount(), "password"));
        tfPassword.setResetPassword(false);
        tfPassword.add(new PropertyValidator<>());
        tfPassword.setLabel(new ResourceModel("person.password"));
        form.add(tfPassword);

        final TextField<String> tfEmail = new TextField<>("email", new PropertyModel<>(student.getId() == null ? newAccount : student.getAccount(), "email"));
        tfEmail.add(EmailAddressValidator.getInstance());
        tfEmail.setLabel(new ResourceModel("person.email"));
        form.add(tfEmail);


        form.add(new SubmitLink("sumbit-link") {
            @Override
            public void onSubmit() {
                super.onSubmit();
                if (student.getId() != null) {
                    personService.saveOrUpdate(student);
                } else {
                    newAccount.setUserType(UserType.STUDENT);
                    //String md5Password = DigestUtils.md5DigestAsHex(acc.getPassword().getBytes());
                    //acc.setPassword(md5Password);
                    userService.createNewUser(student, newAccount);
                }

                StudentsPage page = new StudentsPage(UserType.STUDENT);
                setResponsePage(page);
            }

            @Override
            public void onError() {
                super.onError();
            }
        });

        form.add(new Link<Void>("back-link") {

            @Override
            public void onClick() {
                setResponsePage(new StudentsPage(UserType.STUDENT));
            }
        });

        add(form);
    }

    private TextField<String> createTextField(Person person, String fieldName) {
        final TextField<String> tField = new TextField<>(fieldName, new PropertyModel<>(person, fieldName));
        tField.add(new PropertyValidator<>());
        tField.setLabel(new ResourceModel("person." + fieldName));
        return tField;
    }

    private TextField<Date> createDateField(Person person, String fieldName) {
        final TextField<Date> tField = new TextField<>(fieldName, new PropertyModel<>(person, fieldName));
        tField.add(new PropertyValidator<>());
        tField.setLabel(new ResourceModel("person." + fieldName));
        return tField;
    }
}
